package com.yong.automoguding.component;


import com.yong.automoguding.annotation.RetrofitApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;

/**
 * @author Hes
 */
@Slf4j
public class RetrofitScanner extends ClassPathBeanDefinitionScanner {


    private static Class<? extends RetrofitFactoryBean> retrofitFactoryBeanClass = RetrofitFactoryBean.class;

    public RetrofitScanner(BeanDefinitionRegistry registry) {
        super(registry);
    }


    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
        Set<BeanDefinitionHolder> definitionHolders = super.doScan(basePackages);
        processBeanDefinitions(definitionHolders);
        return definitionHolders;
    }





    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
       // 自定义扫描规则
        AnnotationMetadata metadata = beanDefinition.getMetadata();
        return metadata.isInterface()
                && metadata.isIndependent()
                && metadata.hasAnnotation(RetrofitApi.class.getName());

    }

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        GenericBeanDefinition definition;
        for (BeanDefinitionHolder holder : beanDefinitions) {
            definition = (GenericBeanDefinition) holder.getBeanDefinition();
            String beanClassName = definition.getBeanClassName();
            definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
            definition.setBeanClass(retrofitFactoryBeanClass);
        }
    }

}
